<template>
  <div class="dataEntryMan">
    <MetaSearchForm @on-search="tableSearch">
      <el-form
        ref="paramsManangement_form"
        :model="searchData"
        label-width="80px"
        class="dataEntryMan_searchFrom"
      >
        <el-form-item label="用户" class="dataEntryMan_searchFromItem">
          <el-select
            v-model="searchData.name"
            placeholder="请选择用户"
            filterable
            clearable
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.username"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备" class="dataEntryMan_searchFromItem">
          <el-select
            v-model="searchData.equipmentId"
            placeholder="请选择设备"
            filterable
            clearable
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.value"
              :label="item.equipmentname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测时间" class="dataEntryMan_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="dataEntryManTable"
      class="dataEntryMan_table"
      table-title="录入列表"
      :is-auto-req="false"
      req-method="post"
      :is-manual-paging="true"
      :display-item="displayItem"
      :table-data="dataEntryManTableData"
      :btn-group="btnGroup"
      :line-btn-group="lineBtnGroup"
      @btnClick="tableBtnClick"
      @lineBtnClick="tableInlineBtnClick"
      @pageChange="pageChange"
    />

    <el-dialog
      v-if="paramOptionDialogFlag"
      :title="itemEditData.id && itemEditData.id !== '' ? '编辑' : '新建'"
      :visible.sync="paramOptionDialogFlag"
      width="80%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="editDialogClose"
    >
      <el-form
        ref="itemEditData"
        :model="itemEditData"
        label-width="150px"
        :rules="editRules"
        class="newEntry"
      >
        <el-form-item label="录入设备" prop="equipment">
          <el-select
            v-model="itemEditData.equipment"
            filterable
            placeholder="请选择录入设备"
            style="width: 100%"
            @change="changeEq"
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.equipmentname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="inputForm">
          <el-form-item
            :label="item.paramname"
            v-for="(item, index) in paramsList_show"
            :key="index"
            class="inputFormItem"
          >
            <el-input
              v-model="item.paramvalue"
              type="number"
              @input="change($event)"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="检测时间" prop="time">
          <el-select v-model="itemEditData.time" placeholder="请选择" @change="chooseCid">
            <el-option
              v-for="item in dateList"
              :key="item.cid"
              :label="item.saveTime"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="editDialogClose()">取消</el-button>
        <el-button type="primary" size="mini" @click="dataDialogSubmit('itemEditData')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :visible.sync="importDialogFlag"
      v-if="importDialogFlag"
      width="width"
      title="数据导入"
      :before-close="importClose"
      center
    >
      <div>
        <el-form
          ref="itemEditData"
          :model="itemEditData"
          label-width="150px"
          :rules="editRules"
        >
          <el-form-item label="录入设备" prop="equipment">
            <el-select
              v-model="itemEditData.equipment"
              placeholder="请选择录入设备"
              style="width: 100%"
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件上传" prop="upload">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="{
                'x-auth-token': token,
              }"
              :data="importData"
              :limit="1"
              :file-list="fileList"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary">上传文件并保存</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlsx或xls格式文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <!-- <div slot="footer">
        <el-button @click="importDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="importDialogFlag = false"
          >确 定</el-button
        >
      </div> -->
    </el-dialog>
    <!-- 导出对话框 -->
    <el-dialog title="导出" :visible.sync="exportDialogFlag" width="60%" center modal>
      <div class="exportForm">
        <el-form :model="exportForm" label-width="150px">
          <el-form-item label="设备">
            <el-select
              v-model="exportForm.equipmentId"
              placeholder="请选择设备"
              filterable
              clearable
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据录入时间">
            <el-date-picker
              v-model="exportFormTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="chooseTime"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer">
        <el-button @click="exportCancel">取 消</el-button>
        <el-button type="primary" @click="exportFinish">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MetaPageTable from "../components/MetaPageTable";
import MetaSearchForm from "../components/MetaSearchForm";
import deepClone from "../utils/deepClone";
export default {
  name: "dataEntryMan",
  components: {
    MetaPageTable,
    MetaSearchForm,
  },
  data() {
    return {
      token: localStorage.getItem("token"),
      uploadUrl: process.env.PROGOO_GATE_WATER + "admin/excel/import",
      paramOptionDialogFlag: false,
      reqUrl: process.env.PROGOO_GATE_WATER + "admin/dataList",
      itemEditData: {
        id: "",
        equipment: "",
        time: "",
      },
      searchData: {
        equipmentId: "",
        dateBetween: "",
        username: "",
        time: [],
      },
      searchDataForTable: {
        username: "",
      },
      editRules: {
        equipment: [{ required: true, message: "请输入录入设备", trigger: "blur" }],
        params: [{ required: true, message: "请选择录入参数", trigger: "blur" }],
        time: [{ required: true, message: "请输入录入时间", trigger: "blur" }],
      },
      dataEntryManTableData: {},

      displayItem: [
        {
          label: "设备",
          prop: "equipmentId",
          type: "enum",
          enums: [],
        },
        {
          label: "录入用户",
          prop: "username",
          type: "enum",
          enums: [],
          width: "80px",
        },
        {
          label: "检测时间",
          prop: "pickTime",
          width: 160,
        },
        {
          label: "编辑时间",
          prop: "modifyTime",
          width: 160,
        },
      ],
      btnGroup: [
        {
          id: "export",
          title: "导出",
        },
        {
          id: "template",
          title: "模板下载",
        },
        {
          id: "import",
          title: "导入",
        },
        {
          id: "add",
          title: "新建",
        },
      ],
      lineBtnGroup: [
        {
          id: "edit",
          title: "编辑",
        },
        {
          id: "delete",
          title: "删除",
        },
      ],
      equipmentList: [],
      paramsList: [],
      userList: [],
      params: "",
      importDialogFlag: false,
      exportDialogFlag: false,
      exportForm: {
        equipmentId: "",
      },
      exportFormTime: "",
      dateList: "",
      importData: {
        eid: "",
        username: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      fileList: [],
    };
  },
  created() {},
  mounted() {
    this.getPermission();
    this.getUser(() => {
      this.getParams(() => {
        this.initTableData(1, true);
      });
    });
    this.getEquipment();
  },
  methods: {
    getPermission() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/content/button",
        method: "get",
      }).then((res) => {
        if (res.data.code === 200) {
          if (res.data.result == "yes") {
            //管理员登录
          } else {
            //非管理员登录
            this.$router.push("/dataEntry");
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.result,
          });
        }
      });
    },
    initTableData(page, reflash) {
      let params = {};
      params = this.searchDataForTable;
      params.page = page;
      params.limit = 10;
      params.sortType = "";
      params.sortOrderBy = "";
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/dataList",
        method: "post",
        data: params,
      }).then((res) => {
        if (res.data.code === 200) {
          this.dataEntryManTableData = {};
          this.dataEntryManTableData.page = page;
          this.dataEntryManTableData.totalElements = res.data.result.totalElements;
          this.dataEntryManTableData.content = res.data.result.content;
          for (let i in this.dataEntryManTableData.content) {
            this.dataEntryManTableData.content[i].tempParamJson = JSON.parse(
              this.dataEntryManTableData.content[i].paramJson
            );
            for (let key in this.dataEntryManTableData.content[i].tempParamJson) {
              this.dataEntryManTableData.content[i][
                key
              ] = this.dataEntryManTableData.content[i].tempParamJson[key];
            }
          }
          this.$nextTick(() => {
            this.$refs.dataEntryManTable.formDataInit(
              reflash,
              this.dataEntryManTableData
            );
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    beforeUpload(file) {
      let excelfileExtend = ".xlsx.xls"; //设置文件格式
      let fileExtend = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.$message.error("文件格式错误");
        return;
      }
      this.importData.eid = this.itemEditData.equipment;
      this.importData.username = localStorage.getItem("username");
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.fileList = [];
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
        });
        this.itemEditData = {};
        this.importDialogFlag = false;
        this.$nextTick(() => {
          this.initTableData(1, true);
        });
      } else {
        this.itemEditData = {};

        this.fileList = [];

        this.$notify({
          title: "失败",
          message: "导入失败",
          type: "error",
        });
      }
    },
    tableBtnClick(item) {
      if (item.button === "add") {
        this.paramOptionDialogFlag = true;
      } else if (item.button === "template") {
        window.open(process.env.PROGOO_FILE + "data_import.xlsx");
      } else if (item.button === "import") {
        this.importDialogFlag = true;
      } else if (item.button === "export") {
        //数据导出
        this.exportDialogFlag = true;
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === "edit") {
        this.paramOptionDialogFlag = true;
        this.itemEditData = {
          id: item.rows.id,
          equipment: item.rows.equipmentId,
          time: item.rows.pickTime,
        };
        for (let i in this.paramsList) {
          this.paramsList_show[i] = this.paramsList[i];
          if (item.rows[this.paramsList[i].paramkey] !== null) {
            for (let j in this.paramsList) {
              this.itemEditData[this.paramsList[j].paramkey] =
                item.rows[this.paramsList[j].paramkey];
              this.paramsList_show[j].paramvalue = item.rows[this.paramsList[j].paramkey];
            }
          }
        }
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "admin/content/edit/" + item.rows.id,
          method: "get",
        }).then((res) => {
          if (res.data.code === 200) {
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.result,
            });
          }
        });
      } else if (item.button === "delete") {
        this.$confirm("确认删除本条数据？数据删除后无法找回", "确认删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "delete/data/" + item.rows.id,
            method: "delete",
          }).then((res) => {
            if (res.data.code === 200) {
              this.$notify.success({
                title: "成功",
                message: "已成功删除本条数据",
              });
              this.$nextTick(() => {
                this.initTableData(1, true);
              });
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.result,
              });
            }
          });
        });
      }
    },
    tableSearch() {
      let param = {};
      for (let key in this.searchData) {
        if (key === "dateBetween") {
          param.dateStart =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][0]
              : "";
          param.dateEnd =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][1]
              : "";
          this.searchData.time = [];
          this.searchData.time[0] = param.dateStart;
          this.searchData.time[1] = param.dateEnd;
        } else {
          param[key] = this.searchData[key];
        }
      }
      this.searchDataForTable = param;
      this.$nextTick(() => {
        this.initTableData(1, true);
      });
    },
    pageChange(e) {
      this.initTableData(e, false);
    },
    chooseTime(e) {
      this.exportForm.dateStart = e[0];
      this.exportForm.dateEnd = e[1];
    },
    exportFinish() {
      let token = localStorage.getItem("token");
      let username = localStorage.getItem("username");

      let params = {};
      params.username = username;
      params.equipmentId = this.exportForm.equipmentId;
      params.dateStart = this.exportForm.dateStart;
      params.dateEnd = this.exportForm.dateEnd;

      this.axios({
        method: "post",
        url: process.env.PROGOO_GATE_WATER + "admin/excel/download ",
        data: params,
        // token
        headers: {
          "x-auth-token": token,
        },
        responseType: "blob",
      }).then((res) => {
        if (res.data.code && res.data.code == 400) {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
          return;
        }
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "录入数据.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.exportDialogFlag = false;
      });
    },
    exportCancel() {
      this.exportForm = {};
      this.exportDialogFlag = false;
    },
    editDialogClose() {
      for (let i in this.paramsList_show) {
        this.paramsList_show[i].paramvalue = "";
      }
      this.itemEditData = {};
      this.paramOptionDialogFlag = false;
    },
    change(e) {
      //强制刷新组件
      this.$forceUpdate();
    },
    changeEq(value) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "reflectivity/time",
        method: "post",
        data: { equipmentId: value },
      }).then((res) => {
        if (res.data.code == 200) {
          this.dateList = res.data.result;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    chooseCid(value) {
      this.itemEditData.cid = value.cid;
      this.itemEditData.time = value.saveTime;
    },
    dataDialogSubmit(formName) {
      let username = localStorage.getItem("username");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {};
          params.id = this.itemEditData.id;
          params.username = username;
          params.equipmentId = this.itemEditData.equipment;
          params.pickTime = this.itemEditData.time;
          params.reflectivityCid = this.itemEditData.cid;
          let tempParam = {};
          for (let i in this.paramsList) {
            if (!this.paramsList_show[i].paramvalue) {
              this.paramsList_show[i].paramvalue = "";
            }
            tempParam[this.paramsList[i].paramkey] = this.paramsList_show[i].paramvalue;
          }
          let temp = JSON.stringify(tempParam);
          params.paramJson = temp;

          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "admin/content/input",
            method: "post",
            data: params,
          }).then((res) => {
            if (res.data.code === 200) {
              this.$notify.success({
                title: "上传成功",
                message: res.data.message,
              });
              this.paramOptionDialogFlag = false;
              this.$nextTick(() => {
                this.initTableData(1, true);
                this.itemEditData = {};
                for (let i in this.paramsList_show) {
                  this.paramsList_show[i].paramvalue = "";
                }
                // this.paramsList = [];
              });
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: "请选择设备/参数/时间",
          });
        }
      });
    },
    getEquipment() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/user",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.data.code === 200) {
          this.equipmentList = res.data.result;
          for (let k in this.displayItem) {
            if (this.displayItem[k].prop === "equipmentId") {
              this.displayItem[k].enums = [];
              for (let l in this.equipmentList) {
                let item = this.equipmentList[l];
                item.value = this.equipmentList[l].id;
                item.text = this.equipmentList[l].equipmentname;
                this.displayItem[k].enums.push(item);
              }
            }
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    getParams(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/paramThreshold",
        method: "post",
        data: {
          page: 1,
          limit: 999,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.paramsList = res.data.result.content;
          this.paramsList.reverse();
          this.paramsList_show = deepClone(this.paramsList);

          for (let i in this.paramsList) {
            this.displayItem.push(this.paramsList[i]);
          }
          for (let j = 4; j < this.displayItem.length; j++) {
            this.displayItem[j].prop = this.displayItem[j].paramkey;
            this.displayItem[j].width = "80px";

            this.displayItem[j].label = this.displayItem[j].paramname;
          }

          // this.$nextTick(() => {
          //   this.$refs.dataEntryTable.formDataInit(reflash, this.dataEntryTableData);
          // });
          if (callback && typeof callback === "function") {
            callback();
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    getUser(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/user/list",
        method: "get",
        data: {
          page: 1,
          limit: 999,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.userList = res.data.result;
          for (let k in this.displayItem) {
            if (this.displayItem[k].prop === "username") {
              this.displayItem[k].enums = [];
              for (let l in this.userList) {
                let item = {};
                item.value = this.userList[l].username;
                item.text = this.userList[l].name;
                this.displayItem[k].enums.push(item);
              }
              break;
            }
          }
          if (callback && typeof callback === "function") {
            callback();
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    excelExport(datas) {
      require.ensure([], () => {
        const tHeader = [];
        let dHeader = [];
        dHeader = datas[0].modelName.split(",");
        tHeader.push("设备");
        for (let i in dHeader) {
          tHeader.push(dHeader[i]);
        }
        tHeader.push("采集时间");

        const filterVal = [];
        let modelKey = [];
        modelKey = datas[0].modelKey.split(",");
        filterVal.push("equipment_name");
        for (let i in modelKey) {
          filterVal.push(modelKey[i]);
        }
        filterVal.push("save_time");
        // 数据集
        const list = datas;
        const data = this.formatJson(filterVal, list);
        // excel名称可自定义
        const excelName = "已录入数据列表";
        this.$export_json_to_excel(tHeader, data, excelName);
      });
    },
    //格式化json
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    importClose() {
      this.importDialogFlag = false;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.dataEntryMan {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .dataEntryMan_table {
    width: 100%;
    overflow-y: unset;
  }
  .dataDetailsForm_item {
    line-height: normal;
    padding: 8px 0;
  }
  .dataEntryMan_searchFrom {
    width: 100%;
  }
  .dataEntryMan_searchFromItem {
    float: left;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
  .newEntry {
    width: 100%;
    .inputForm {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      .inputFormItem {
        width: 25%;
      }
    }
  }
}
</style>
